package com.ruoyi.system.controller;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.SysBillDetails;
import com.ruoyi.system.domain.SysComboMeal;
import com.ruoyi.system.domain.SysMember;
import com.ruoyi.system.domain.SysMemberRai;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.ISysMemberService;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 会员信息Controller
 * 
 * @author ruoyi
 * @date 2025-04-21
 */
@Api("会员信息")
@RestController
@Anonymous
@RequestMapping("/system/member")
public class SysMemberController extends BaseController
{
    @Autowired
    private ISysMemberService sysMemberService;

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private SysDictDataMapper sysDictDataMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUserServiceImpl sysUserServiceImpl;
    @Autowired
    private SysBillDetailsMapper sysBillDetailsMapper;
    @Autowired
    private SysMemberMapper sysMemberMapper;
    @Autowired
    private SysComboMealMapper sysComboMealMapper;
    /**
     * 查询会员信息列表
     */
    @ApiOperation("查询会员信息列表")
    // @PreAuthorize("@ss.hasPermi('system:member:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysMember sysMember)
    {
        startPage();
        List<SysMember> list = sysMemberService.selectSysMemberList(sysMember);
        return getDataTable(list);
    }

    /**
     * 导出会员信息列表
     */
    @ApiOperation("导出会员信息列表")
    // @PreAuthorize("@ss.hasPermi('system:member:export')")
    @Log(title = "会员信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysMember sysMember)
    {
        List<SysMember> list = sysMemberService.selectSysMemberList(sysMember);
        for (SysMember sysMember1 : list) {
            String sysUserSex = sysDictDataMapper.selectDictLabel("sys_user_sex", sysMember1.getMemberSex());
            sysMember1.setMemberSexCh(sysUserSex);
        }
        ExcelUtil<SysMember> util = new ExcelUtil<SysMember>(SysMember.class);
        util.exportExcel(response, list, "会员信息数据");
    }

    /**
     * 获取会员信息详细信息
     */
    @ApiOperation("获取会员信息详细信息")
    // @PreAuthorize("@ss.hasPermi('system:member:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(sysMemberService.selectSysMemberById(id));
    }


    /**
     * 新增会员信息
     */
    @ApiOperation("新增会员信息")
    // @PreAuthorize("@ss.hasPermi('system:member:add')")
    @Log(title = "会员信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysMember sysMember)
    {
        if (ObjectUtils.isNotEmpty(sysMember.getMemberName())){
//            SysMember param = new SysMember();
//            param.setMemberName(sysMember.getMemberName());
            // TODO 默认金额，支付后修改
            sysMember.setAccountBalance(sysMember.getAccountBalance());
//            if (ObjectUtils.isNotEmpty(sysMemberService.selectSysMemberList(param))){
//                return error("用户昵称不允许重复");
//            }
        }
        return toAjax(sysMemberService.insertSysMember(sysMember));
    }

    /**
     * 注册用户
     */
    @Anonymous
    @Log(title = "会员信息", businessType = BusinessType.INSERT)
    @PostMapping("/register")
    public AjaxResult register(@RequestBody SysMember sysMember)
    {
        Object cacheObject = redisCache.getCacheObject("sms_code:" + sysMember.getPhonenumber());
        if (ObjectUtils.isEmpty(sysMember.getPhonenumber()) || ObjectUtils.isEmpty(sysMember.getCode())){
            return AjaxResult.error("请正确注册用户");
        }
        if (ObjectUtils.isEmpty(cacheObject)){
            return AjaxResult.error("请获取验证码！");
        }
        if (!sysMember.getCode().equals(cacheObject.toString())){
            return AjaxResult.error("验证码错误");
        }
        sysMember.setMemberName(ObjectUtils.isNotEmpty(sysMember.getMemberName()) ? sysMember.getMemberName() : sysMember.getPhonenumber());
       sysMemberService.insertSysMemberRtnId(sysMember);
        return AjaxResult.success(sysMember.getId());
    }

    /**
     * 修改会员信息
     */
    @ApiOperation("修改会员信息")
    // @PreAuthorize("@ss.hasPermi('system:member:edit')")
    @Log(title = "会员信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysMember sysMember)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        sysMember.setUpdateBy(user.getUserId() + "");
        return toAjax(sysMemberService.updateSysMember(sysMember));
    }

    /**
     * 删除会员信息
     */
    @ApiOperation("删除会员信息")
    // @PreAuthorize("@ss.hasPermi('system:member:remove')")
    @Log(title = "会员信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(sysMemberService.deleteSysMemberByIds(ids));
    }

    @GetMapping("/listById/{id}")
    public AjaxResult getMemberUseRai(@PathVariable("id") String id){
        List<SysMemberRai> res = sysMemberService.getMemberUseRai(id);
        return AjaxResult.success(res);
    }

    @GetMapping("/listByRaiId/{id}/{raiId}")
    public AjaxResult getMemberByUseRai(@PathVariable("id") String id, @PathVariable("raiId") String raiId){
        List<SysMemberRai> res = sysMemberService.getMemberUserRaiList(id,raiId);
        return AjaxResult.success(res);
    }

    public static void main(String[] args) {
        String replace = UUID.randomUUID().toString().replace("-", "");
        System.out.println(replace);
    }

    @PostMapping("/addMember")
    @Anonymous
    public AjaxResult addMember(@RequestBody SysMember sysMember) {
        SysMember param = new SysMember();
        param.setPhonenumber(sysMember.getPhonenumber());
        // 判断手机号是否存在
        List<SysMember> list = sysMemberService.selectSysMemberList(param);
        if (ObjectUtils.isNotEmpty(list)){
            return AjaxResult.error("该手机号已是会员！");
        }
        // 新增会员，h5登录后直接变成会员
        if (ObjectUtils.isEmpty(sysMember.getCumulativeMoney())){
            sysMember.setCumulativeMoney("0.00");
        }
        if (ObjectUtils.isEmpty(sysMember.getStatus())){
            sysMember.setStatus("1");
        }
        if (ObjectUtils.isEmpty(sysMember.getMemberSex())){
            sysMember.setMemberSex("1");
        }

        SysUser sysUser = sysUserMapper.checkPhoneUnique(sysMember.getPhonenumber());
        // 判断用户是否存在，没有新增用户
        if (ObjectUtils.isEmpty(sysUser)){
            // 查询会员套餐配置 sysComboMeals
            List<SysComboMeal> sysComboMeals = sysComboMealMapper.selectSysComboMealList(new SysComboMeal());
            String balance = sysComboMeals.get(0).getComboMealAmount();
            Date now = new Date();
            sysUser = new SysUser();
            sysUser.setDeptId(104L);
            sysUser.setNickName("会员");
            sysUser.setUserName(sysMember.getPhonenumber());
            sysUser.setPhonenumber(sysMember.getPhonenumber());
            sysUser.setPassword(new BCryptPasswordEncoder().encode("123456"));
            sysUser.setStatus("0");
            sysUser.setDelFlag("0");
            sysUser.setRoleId(2L);
            Long[] longs = new Long[1];
            longs[0] = 2L;
            sysUser.setRoleIds(longs);
            sysUser.setSex("1");
            sysUser.setCreateBy("1");
            sysUser.setCreateTime(now);
            sysUser.setUpdateBy("1");
            sysUser.setUpdateTime(now);
            sysUserServiceImpl.insertUser(sysUser);
            // 新增会员账单明细，开通会员赠送金额
            sysMember.setPhonenumber(sysMember.getPhonenumber());
            sysMember.setMemberName(ObjectUtils.isNotEmpty(sysMember.getMemberName()) ? sysMember.getMemberName() : sysMember.getPhonenumber());
            sysMember.setStatus("1");
            // 计算会员过期时间
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(now);
            calendar.add(Calendar.DATE, (Integer.parseInt(sysComboMeals.get(0).getMemberDay()) + 1));
            Date endTime = calendar.getTime();
            sysMember.setMemberEndDate(endTime);
            // 累计金额为0
            sysMember.setCumulativeMoney("0.00");
            // 赠送金额 赠送金额为开通套餐金额
            sysMember.setAccountBalance(balance);
            int i = sysMemberService.insertSysMemberRtnId(sysMember);
            if (i > 0){
//                List<SysComboMeal> sysComboMeals = sysComboMealMapper.selectSysComboMealList(new SysComboMeal());
//                String balance = sysComboMeals.get(0).getComboMealAmount();
                SysMember memberParam = sysMemberMapper.selectSysMemberByPhone(sysMember.getPhonenumber());
                String id = memberParam.getId();
                SysBillDetails sysBillDetails = new SysBillDetails();
                sysBillDetails.setMatterType("开通会员");
                sysBillDetails.setAccountBalance(balance);
                sysBillDetails.setBalanceChanges("+" + balance);
                sysBillDetails.setMemberId(id);
                sysBillDetails.setCreateTime(new Date());
                sysBillDetails.setUpdateTime(new Date());
                sysBillDetailsMapper.insertSysBillDetails(sysBillDetails);
            }
        }
        return AjaxResult.success();
    }

    /**
     * 注册用户
     */
    @Anonymous
    @Log(title = "会员信息", businessType = BusinessType.INSERT)
    @PostMapping("/share")
    public AjaxResult share(@RequestBody SysMember sysMember)
    {
       if (ObjectUtils.isEmpty(sysMember.getOpenId())){
            return AjaxResult.error("找不到被分享者信息！");
        }
        if (ObjectUtils.isEmpty(sysMember.getShareId())){
            return AjaxResult.error("找不到分享者信息！");
        }
        SysMember param = new SysMember();
        param.setOpenId(sysMember.getOpenId());
        List<SysMember> sysMembers = sysMemberMapper.selectSysMemberList(param);
        if (ObjectUtils.isNotEmpty(sysMembers)){
            return AjaxResult.error("该用户已存在！");
        }
        // 新建会员
        Date now = new Date();
        SysUser sysUser = new SysUser();
        sysUser.setDeptId(104L);
        sysUser.setNickName("用户");
        sysUser.setUserName("用户");
        sysUser.setPhonenumber("");
        sysUser.setPassword(new BCryptPasswordEncoder().encode("123456"));
        sysUser.setStatus("0");
        sysUser.setDelFlag("0");
        sysUser.setRoleId(2L);
        Long[] longs = new Long[1];
        longs[0] = 2L;
        sysUser.setRoleIds(longs);
        sysUser.setSex("1");
        sysUser.setCreateBy("1");
        sysUser.setCreateTime(now);
        sysUser.setUpdateBy("1");
        sysUser.setUpdateTime(now);
        sysUserServiceImpl.insertUser(sysUser);
        SysMember sysMemberParam = new SysMember();
        sysMemberParam.setOpenId(sysMember.getOpenId());
        sysMemberParam.setInviteBy(sysMember.getShareId());
        sysMemberParam.setStatus("0");
        sysMemberParam.setCreateTime(now);
        sysMemberParam.setUpdateTime(now);
        sysMemberMapper.insertSysMember(sysMemberParam);
        return AjaxResult.success();
    }

    @GetMapping("/shareList/{id}")
    public AjaxResult shareList(@PathVariable("id") String id){
        SysMember param = new SysMember();
        param.setInviteBy(id);
        return AjaxResult.success(sysMemberMapper.selectSysMemberList(param));
    }

}
